package com.example.demo.controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.ArtDiscuss;
import com.example.demo.entity.Userinfo;
import com.example.demo.service.DiscussService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/dis")
public class DiscussController {

    @Autowired
    private DiscussService discussService;
    @Autowired
    private UserService userService;

    // 添加评论
    @RequestMapping("/setdis")
    public AjaxResult insDetail(ArtDiscuss artDiscuss, HttpServletRequest request) {
        // 非空校验
        if (artDiscuss == null ||  artDiscuss.getId() <= 0
                        || !StringUtils.hasLength(artDiscuss.getDiscuss())) {
            return AjaxResult.fail(-1, "非法参数");
        }
        if (artDiscuss.getDiscuss().length() > 66) {
            return AjaxResult.fail(-2, "字数过多!");
        }
        // 拿到登录对象
        Userinfo userinfo = UserSessionUtils.getUser(request);
        if (userinfo == null) {
            // 登录才可以评论.
            return AjaxResult.fail(-3, "非法用户访问!");
        }
        // 设置评论对象的属性
        artDiscuss.setNickname(userService.getNickName(userinfo.getId()));
        artDiscuss.setUid(userinfo.getId());
        artDiscuss.setUserphoto(userinfo.getPhoto());
        // 将评论相关内容存到数据库中
        return AjaxResult.success(discussService.insDetail(artDiscuss));
    }

    /**
     *  获取评论
     * @param id 文章id
     * @return 评论列表
     */
    @RequestMapping("/getdis") // 文章id
    public AjaxResult getDetail(Integer id) {
        if (id <= 0) {
            return AjaxResult.fail(-1, "非法参数");
        }
        List<ArtDiscuss> list = discussService.getDetail(id);
        return AjaxResult.success(list);
    }

}
